package com.beyond.market.user.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//声明此类是一个配置类 == ssm ->spring-shiro.xml配置文件
@Configuration
public class ShiroConfig {

    /**
     * 1.提供一个Realm
     * <bean id="userRealm" class="com.ssm.realm.UserRealm"/>
     */
    @Bean(name="userRealm")
    public UserRealm getUserRealm(){
        return new UserRealm();
    }

    /**
     *  2.提供一个SecurityManager安全管理器
     *  <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
     *     <property name="realm" ref="userRealm"/>
     *  </bean>
     */
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 3.提供一个ShiroFilterFactoryBean
     */
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")
                                                   DefaultWebSecurityManager dwm){
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(dwm);

        //对没有登录进行过滤
        Map<String,String> filterMap = new HashMap<>();
        //1.添加对/add,/remove必须登录过才可以
        filterMap.put("/add","authc");
        filterMap.put("/remove","authc");
        filterMap.put("/**","anon");
        //如果某些路径必须需要登录才能通过，否则跳转到LoginUrl
        shiroFilter.setLoginUrl("/login");

        //判断权限过滤器
        filterMap.put("/add","perms[user:add]");
        filterMap.put("/remove","perms[user:remove]");
        //如果没有权限则跳转到未识别路径
        shiroFilter.setUnauthorizedUrl("/unauthorizedUrl");


        //把过滤的map设置给shiroFilter
        shiroFilter.setFilterChainDefinitionMap(filterMap);
        return shiroFilter;
    }


    /**
     * 创建一个Shiro方言对象
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
